# -*- coding: utf-8 -*-
from decimal import Decimal, InvalidOperation

from django.http import HttpResponse
from django.shortcuts import render_to_response, HttpResponseRedirect,redirect,get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site, RequestSite
from django.conf import settings

from registration.models import get_profile
from store.alipay import Alipay
from store.models import Category,Card,CardOrder
from store.forms import CardForm

def card_list(request,id=None,template_name='store/card_list.html',extra_context={}):
    categories = Category.publish.all()
    if id:
        cards = Card.publish.filter(category__id=id).select_related()
    else:
        cards = Card.publish.all().select_related()
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'cards': cards},
                              context_instance=context)

def card_detail(request,id,template_name='store/card_detail.html',extra_context={}):
    card = Card.publish.get(id=id)
    if request.method == 'POST':
        request.session["quantity"] = request.POST.get('quantity','1')
        return redirect('card_buy',id=id)
    return render_to_response(template_name,
                              {'card': card},
                               context_instance=RequestContext(request))

@login_required
def card_buy(request,id,template_name='store/card_buy.html',extra_context={}):
    quantity = request.session.get("quantity","1")
    card = Card.publish.get(id=id)
    limit,discount = get_profile(request.user)
    if request.method == 'POST':
        form = CardForm(user=request.user,data=request.POST)
        if form.is_valid():
            quantity = form.cleaned_data.get('quantity')
            order = CardOrder.objects.create_order(card, quantity, request.user, request.META["REMOTE_ADDR"])
            return redirect('alipay_pay',id=order.id)
    else:
        form = CardForm(user=request.user,data={'quantity':quantity})
        if not form.is_valid():
            quantity = 1
    return render_to_response(template_name,
                          {'card': card,
                           'form':form,
                           'limit':limit,
                           'discount':discount,
                           'quantity':quantity},
                           context_instance=RequestContext(request))
@login_required
def alipay_pay(request,id):
    order = CardOrder.objects.get(id=id)
    seller_email = settings.ALIPAY_SELLER_EMAIL;
    subject = order.product_name
    body = order.product_name
    out_trade_no = order.code
    total_fee = order.total_amount
    domain = RequestSite(request).domain
    notify_url = 'http://%s%s' % (domain,reverse('alipay_notify'))
    payment_type = "2"
    if seller_email and subject and out_trade_no and total_fee and notify_url and payment_type:
        alipay = Alipay()
        request_url = alipay.create_direct_pay_by_user_url(seller_email, subject, body, out_trade_no, total_fee, notify_url, payment_type)
    return HttpResponseRedirect(request_url)

def alipay_notify(request):
    pass
